package v1

import (
	"net/http"
	"strconv"

	"gitee.com/daonna/collab-manage-system/service"

	"github.com/gin-gonic/gin"
)

// CreateGroup 创建群组
func CreateGroup(c *gin.Context) {
	// 获取当前用户ID（创建者）
	currentUserID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":    401,
			"message": "未授权操作",
		})
		return
	}

	// 解析请求体
	var req struct {
		Name        string  `json:"name" binding:"required,max=100"`
		Description string  `json:"description" binding:"omitempty"`
		AvatarURL   string  `json:"avatar_url" binding:"omitempty,max=255"`
		MemberIDs   []int64 `json:"member_ids" binding:"omitempty"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的请求参数: " + err.Error(),
		})
		return
	}

	// 调用服务层创建群组
	groupID, err := service.CreateGroup(c.Request.Context(), currentUserID.(uint), req.Name, req.Description, req.AvatarURL, req.MemberIDs)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "创建群组失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "创建群组成功",
		"data": gin.H{
			"group_id": groupID,
		},
	})
}

// DeleteGroup 删除群组
func DeleteGroup(c *gin.Context) {
	// 获取群组ID
	groupID, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的群组ID",
		})
		return
	}

	// 获取当前用户ID（操作者）
	currentUserID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":    401,
			"message": "未授权操作",
		})
		return
	}

	// 调用服务层删除群组
	err = service.DeleteGroup(c.Request.Context(), uint(groupID), currentUserID.(uint))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "删除群组失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "删除群组成功",
	})
}

// UpdateGroup 更新群组信息
func UpdateGroup(c *gin.Context) {
	// 获取群组ID
	groupID, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的群组ID",
		})
		return
	}

	// 获取当前用户ID（操作者）
	currentUserID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":    401,
			"message": "未授权操作",
		})
		return
	}

	// 解析请求体
	var req struct {
		Name        string `json:"name" binding:"omitempty,max=100"`
		Description string `json:"description" binding:"omitempty"`
		AvatarURL   string `json:"avatar_url" binding:"omitempty,max=255"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的请求参数: " + err.Error(),
		})
		return
	}

	// 调用服务层更新群组信息
	err = service.UpdateGroup(c.Request.Context(), uint(groupID), currentUserID.(uint), req.Name, req.Description, req.AvatarURL)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "更新群组失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "更新群组成功",
	})
}

// ListGroups 获取群组列表
func ListGroups(c *gin.Context) {
	// 获取当前用户ID
	currentUserID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":    401,
			"message": "未授权操作",
		})
		return
	}

	// 调用服务层获取群组列表
	groups, err := service.ListGroups(c.Request.Context(), currentUserID.(uint))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "获取群组列表失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "获取群组列表成功",
		"data":    groups,
	})
}

// GetGroup 获取群组信息
func GetGroup(c *gin.Context) {
	// 获取群组ID
	groupID, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的群组ID",
		})
		return
	}

	// 获取当前用户ID
	currentUserID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":    401,
			"message": "未授权操作",
		})
		return
	}

	// 调用服务层获取群组信息
	group, err := service.GetGroup(c.Request.Context(), uint(groupID), currentUserID.(uint))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "获取群组失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "获取群组成功",
		"data":    group,
	})
}

// ListGroupMembers 获取群组成员列表
func ListGroupMembers(c *gin.Context) {
	// 获取群组ID
	groupID, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的群组ID",
		})
		return
	}

	// 调用服务层获取群组成员
	members, err := service.GetGroupMembers(c.Request.Context(), groupID)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "获取群组成员失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "获取群组成员成功",
		"data":    members,
	})
}

//获取单聊列表
func GetSingleChatList(c *gin.Context) {
	// 获取当前用户ID
	currentUserID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":    401,
			"message": "未授权操作",
		})
		return
	}

	// 调用服务层获取单聊列表
	chats, err := service.ListPrivateChats(c.Request.Context(), currentUserID.(uint))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "获取单聊列表失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "获取单聊列表成功",
		"data":    chats,
	})
}

// AddGroupMember 添加群组成员
func AddGroupMember(c *gin.Context) {
	// 获取群组ID
	groupID, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的群组ID",
		})
		return
	}

	// 获取当前用户ID（操作者）
	currentUserID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":    401,
			"message": "未授权操作",
		})
		return
	}

	// 解析请求体
	var req struct {
		UserID int64  `json:"user_id" binding:"required"`
		Role   string `json:"role" binding:"omitempty,oneof=member admin"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的请求参数: " + err.Error(),
		})
		return
	}

	// 调用服务层添加群组成员
	err = service.AddGroupMember(c.Request.Context(), uint(groupID), currentUserID.(uint), uint(req.UserID), req.Role)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "添加群组成员失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "添加群组成员成功",
	})
}

// RemoveGroupMember 移除群组成员
func RemoveGroupMember(c *gin.Context) {
	// 获取群组ID和要移除的用户ID
	groupID, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的群组ID",
		})
		return
	}

	userID, err := strconv.ParseInt(c.Param("userId"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的用户ID",
		})
		return
	}

	// 获取当前用户ID（操作者）
	currentUserID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":    401,
			"message": "未授权操作",
		})
		return
	}

	// 调用服务层移除群组成员
	err = service.RemoveGroupMember(c.Request.Context(), uint(groupID), currentUserID.(uint), uint(userID))
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "移除群组成员失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "移除群组成员成功",
	})
}

// UpdateMemberRole 更新群组成员角色
func UpdateMemberRole(c *gin.Context) {
	// 获取群组ID和要更新的用户ID
	groupID, err := strconv.ParseInt(c.Param("id"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的群组ID",
		})
		return
	}

	userID, err := strconv.ParseInt(c.Param("userId"), 10, 64)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的用户ID",
		})
		return
	}

	// 获取当前用户ID（操作者）
	currentUserID, exists := c.Get("user_id")
	if !exists {
		c.JSON(http.StatusUnauthorized, gin.H{
			"code":    401,
			"message": "未授权操作",
		})
		return
	}

	// 解析请求体
	var req struct {
		Role string `json:"role" binding:"required,oneof=member admin owner"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"code":    400,
			"message": "无效的请求参数: " + err.Error(),
		})
		return
	}

	// 调用服务层更新成员角色
	err = service.UpdateMemberRole(c.Request.Context(), uint(groupID), currentUserID.(uint), uint(userID), req.Role)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{
			"code":    500,
			"message": "更新成员角色失败: " + err.Error(),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"code":    200,
		"message": "更新成员角色成功",
	})
}
